import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { UserService } from "../../user/user.service";

// JWT载荷类型
interface JwtPayload {
	sub: number;
	username: string;
	iat?: number;
	exp?: number;
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
	constructor(
		private readonly configService: ConfigService,
		private readonly userService: UserService
	) {
		super({
			jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
			ignoreExpiration: false,
			secretOrKey: configService.get("app.jwtSecret"),
		});
	}

	async validate(payload: JwtPayload) {
		try {
			const user = await this.userService.findOne(payload.sub);
			if (!user) {
				throw new UnauthorizedException("用户不存在");
			}
			return {
				id: user.id,
				username: user.username,
				nickname: user.nickname,
				points: user.points,
				role: user.role,
			};
		} catch (error) {
			throw new UnauthorizedException("认证失败");
		}
	}
}
